package com.acane.instagram.feature.me.account

import android.annotation.SuppressLint
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.theme.InstagramBlue
import com.acane.instagram.core.design.theme.InstagramDarkGray
import com.acane.instagram.core.design.theme.InstagramLightGray
import com.acane.instagram.core.design.theme.LightGrayBackground
import com.acane.instagram.core.design.theme.Spacer
import com.acane.instagram.core.extension.clickableNoRipple
import com.acane.instagram.feature.common.SessionManager
import com.acane.instagram.feature.me.MeViewModel
import kotlinx.coroutines.launch

@Composable
fun EditMeRoute(
    meViewModel: MeViewModel = viewModel(),
    navController: NavController,
) {
    EditMeScreen(
        navController = navController, meViewModel = meViewModel
    )
}

@SuppressLint("UnrememberedMutableState", "StateFlowValueCalledInComposition")
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
@Composable
fun EditMeScreen(
    navController: NavController,
    meViewModel: MeViewModel,
) {
    val genderBottomSheetState =
        rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)

    var inputNickName = meViewModel.currentUserInfo.collectAsState().value.nickName
    var inputUserName = meViewModel.currentUserInfo.collectAsState().value.userName

    var inputSex by remember { mutableStateOf(meViewModel.currentUserInfo.value.sex) }

    var inputIntroduction = meViewModel.currentUserInfo.collectAsState().value.introduction
    var inputBirthday = meViewModel.currentUserInfo.collectAsState().value.birthday
    var inputPhone = meViewModel.currentUserInfo.collectAsState().value.phone
    var inputEmail = meViewModel.currentUserInfo.collectAsState().value.email


    val updatePasswordBottomSheetState =
        rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)

    val scope = rememberCoroutineScope()
    val context = LocalContext.current


    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = "编辑主页",
                        fontWeight = FontWeight.Bold,
                        fontSize = 16.sp,
                    )
                },
                navigationIcon = {
                    IconButton(onClick = {
                        navController.popBackStack()
                    }) {
                        Image(
                            painter = painterResource(id = R.drawable.arrow_left),
                            contentDescription = "返回",
                            modifier = Modifier.size(24.dp),
                            contentScale = ContentScale.Fit
                        )
                    }
                },
                actions = {

                },
                colors = TopAppBarDefaults.centerAlignedTopAppBarColors().copy(
                    containerColor = Color.Transparent
                )
            )
        },
        containerColor = Color.White,
    ) { padding ->


        LaunchedEffect(meViewModel.currentUserInfo.value) {
            // 只有当用户信息被加载时，才更新输入框的值
            inputNickName = meViewModel.currentUserInfo.value.nickName ?: ""
            inputUserName = meViewModel.currentUserInfo.value.userName ?: ""
            inputIntroduction = meViewModel.currentUserInfo.value.introduction ?: ""
            inputPhone = meViewModel.currentUserInfo.value.phone ?: ""
            inputEmail = meViewModel.currentUserInfo.value.email ?: ""
            inputBirthday = meViewModel.currentUserInfo.value.birthday ?: ""
            inputSex = meViewModel.currentUserInfo.value.sex
        }

        val dateFormatter = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault())

        // 在需要的地方设置一个点击事件来打开日期选择器
        val openDatePicker = {
            val calendar = java.util.Calendar.getInstance()

            val datePickerDialog = android.app.DatePickerDialog(
                context,
                { _, year, month, dayOfMonth ->
                    // 当用户选择日期后，更新输入框的日期
                    inputBirthday = "$year-${month + 1}-$dayOfMonth"
                    val newUserInfo = meViewModel.currentUserInfo.value.copy(birthday = inputBirthday)
                    meViewModel.updateUserInfo(newUserInfo, context)
                },
                calendar.get(java.util.Calendar.YEAR),
                calendar.get(java.util.Calendar.MONTH),
                calendar.get(java.util.Calendar.DAY_OF_MONTH)
            )
            datePickerDialog.show()
        }

        Column(
            modifier = Modifier
                .padding(padding)
                .fillMaxSize()
        ) {
            // 头像
            SessionManager.currentUser?.id?.let { UpdateAvatar(it, meViewModel) }
            // 输入框
            Column(
                modifier = Modifier.padding(10.dp)
            ) {
                // 昵称
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "昵称", fontSize = 14.sp, color = InstagramDarkGray,
                        modifier = Modifier.padding(10.dp)
                    )
                    TextField(
                        value = inputNickName.toString(),
                        onValueChange = { inputNickName = it },
                        placeholder = {

                        },
                        modifier = Modifier
                            .weight(1f)
                            .padding(vertical = 8.dp)
                            .heightIn(min = 30.dp, max = 56.dp),
                        colors = TextFieldDefaults.colors(
                            focusedIndicatorColor = LightGrayBackground,
                            unfocusedIndicatorColor = LightGrayBackground,
                            disabledIndicatorColor = LightGrayBackground,
                            unfocusedContainerColor = LightGrayBackground,
                        ),
                        shape = RoundedCornerShape(5.dp),
                    )

                    if (inputNickName != "") {
                        Image(painter = painterResource(id = R.drawable.check),
                            contentDescription = "确认",
                            modifier = Modifier
                                .size(24.dp)
                                .padding(top = 8.dp)
                                .clickable {
                                    // 更新昵称
                                    val newUserInfo =
                                        meViewModel.currentUserInfo.value.copy(nickName = inputNickName)
                                    meViewModel.updateUserInfo(
                                        userInfo = newUserInfo, context = context
                                    )
                                })
                    }
                }

                // 帐户名
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {

                    Text(
                        text = "帐号", fontSize = 14.sp, color = InstagramDarkGray,
                        modifier = Modifier.padding(10.dp)
                    )
                    inputUserName?.let {
                        TextField(
                            value = it,
                            onValueChange = { inputUserName = it },
                            placeholder = {

                            },
                            modifier = Modifier
                                .weight(1f)
                                .padding(vertical = 8.dp)
                                .heightIn(min = 30.dp, max = 56.dp),
                            colors = TextFieldDefaults.colors(
                                focusedIndicatorColor = LightGrayBackground,
                                unfocusedIndicatorColor = LightGrayBackground,
                                disabledIndicatorColor = LightGrayBackground,
                                unfocusedContainerColor = LightGrayBackground,
                            ),
                            shape = RoundedCornerShape(5.dp),
                        )
                    }
                    if (inputUserName != "") {
                        Image(painter = painterResource(id = R.drawable.check),
                            contentDescription = "确认",
                            modifier = Modifier
                                .size(24.dp)
                                .padding(top = 8.dp)
                                .clickable {
                                    // 更新用户名
                                    val newUserInfo =
                                        meViewModel.currentUserInfo.value.copy(userName = inputUserName)
                                    meViewModel.updateUserInfo(
                                        userInfo = newUserInfo, context = context
                                    )
                                })
                    }
                }

                // 简介
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "简介", fontSize = 14.sp, color = InstagramDarkGray,
                        modifier = Modifier.padding(10.dp)
                    )
                    inputIntroduction?.let {
                        TextField(
                            value = it,
                            onValueChange = { inputIntroduction = it },
                            placeholder = {

                            },
                            modifier = Modifier
                                .weight(1f)
                                .padding(vertical = 8.dp)
                                .heightIn(min = 30.dp, max = 56.dp),
                            colors = TextFieldDefaults.colors(
                                focusedIndicatorColor = LightGrayBackground,
                                unfocusedIndicatorColor = LightGrayBackground,
                                disabledIndicatorColor = LightGrayBackground,
                                unfocusedContainerColor = LightGrayBackground,
                            ),
                            shape = RoundedCornerShape(5.dp),
                        )
                    }
                    if (inputIntroduction != "") {
                        Image(painter = painterResource(id = R.drawable.check),
                            contentDescription = "确认",
                            modifier = Modifier
                                .size(24.dp)
                                .padding(top = 8.dp)
                                .clickable {
                                    // 更新简介
                                    val newUserInfo =
                                        meViewModel.currentUserInfo.value.copy(introduction = inputIntroduction)
                                    meViewModel.updateUserInfo(
                                        userInfo = newUserInfo, context = context
                                    )
                                })
                    }
                }
                // 性别
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            scope.launch {
                                genderBottomSheetState.show()
                            }
                        },
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "性别",
                        fontSize = 14.sp,
                        color = InstagramDarkGray,
                        modifier = Modifier.padding(10.dp)
                    )
                    val displaySex = when (meViewModel.currentUserInfo.value.sex) {
                        0 -> "男"
                        1 -> "女"
                        else -> "未知"
                    }
                    displaySex.let {
                        TextField(
                            value = it,
                            onValueChange = {  },
                            placeholder = {

                            },
                            enabled = false,
                            modifier = Modifier
                                .weight(1f)
                                .padding(vertical = 8.dp)
                                .heightIn(min = 30.dp, max = 56.dp)
                                .weight(1f)
                                .clickable {

                                },
                            colors = TextFieldDefaults.colors(
                                focusedIndicatorColor = LightGrayBackground,
                                unfocusedIndicatorColor = LightGrayBackground,
                                disabledIndicatorColor = LightGrayBackground,
                                unfocusedContainerColor = LightGrayBackground,
                            ),
                            shape = RoundedCornerShape(5.dp),
                        )
                    }
                    Image(painter = painterResource(id = R.drawable.arrow_forward),
                        contentDescription = "",
                        modifier = Modifier
                            .size(24.dp)
                            .padding(top = 8.dp)
                            .clickable {
                                scope.launch {
                                    genderBottomSheetState.show()
                                }
                            })
                }
                // 出生日期
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "出生日期", fontSize = 14.sp, color = InstagramDarkGray,
                        modifier = Modifier.padding(10.dp)
                    )
                    inputBirthday?.let {
                        TextField(
                            value = it,
                            onValueChange = { inputBirthday = it },
                            placeholder = {

                            },
                            enabled = false,
                            modifier = Modifier
                                .weight(1f)
                                .padding(vertical = 8.dp)
                                .heightIn(min = 30.dp, max = 56.dp)
                                .clickable {
                                    openDatePicker()
                                },
                            colors = TextFieldDefaults.colors(
                                focusedIndicatorColor = LightGrayBackground,
                                unfocusedIndicatorColor = LightGrayBackground,
                                disabledIndicatorColor = LightGrayBackground,
                                unfocusedContainerColor = LightGrayBackground,
                            ),
                            shape = RoundedCornerShape(5.dp),
                        )
                    }
                }
                // 电话
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "电话", fontSize = 14.sp, color = InstagramDarkGray,
                        modifier = Modifier.padding(10.dp)
                    )
                    inputPhone?.let {
                        TextField(
                            value = it,
                            onValueChange = { inputPhone = it },
                            placeholder = {

                            },
                            modifier = Modifier
                                .weight(1f)
                                .padding(vertical = 8.dp)
                                .heightIn(min = 30.dp, max = 56.dp),
                            colors = TextFieldDefaults.colors(
                                focusedIndicatorColor = LightGrayBackground,
                                unfocusedIndicatorColor = LightGrayBackground,
                                disabledIndicatorColor = LightGrayBackground,
                                unfocusedContainerColor = LightGrayBackground,
                            ),
                            shape = RoundedCornerShape(5.dp),
                        )
                    }
                    if (inputPhone != "") {
                        Image(painter = painterResource(id = R.drawable.check),
                            contentDescription = "确认",
                            modifier = Modifier
                                .size(24.dp)
                                .padding(top = 8.dp)
                                .clickable {
                                    // 更新电话
                                    val newUserInfo =
                                        meViewModel.currentUserInfo.value.copy(phone = inputPhone)
                                    meViewModel.updateUserInfo(
                                        userInfo = newUserInfo, context = context
                                    )
                                })
                    }
                }
                // 邮箱
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "邮箱", fontSize = 14.sp, color = InstagramDarkGray,
                        modifier = Modifier.padding(10.dp)
                    )
                    inputEmail?.let {
                        TextField(
                            value = it,
                            onValueChange = { inputEmail = it },
                            placeholder = {

                            },
                            modifier = Modifier
                                .weight(1f)
                                .padding(vertical = 8.dp)
                                .heightIn(min = 30.dp, max = 56.dp),
                            colors = TextFieldDefaults.colors(
                                focusedIndicatorColor = LightGrayBackground,
                                unfocusedIndicatorColor = LightGrayBackground,
                                disabledIndicatorColor = LightGrayBackground,
                                unfocusedContainerColor = LightGrayBackground,
                            ),
                            shape = RoundedCornerShape(5.dp),
                        )
                    }
                    if (inputEmail != "") {
                        Image(painter = painterResource(id = R.drawable.check),
                            contentDescription = "确认",
                            modifier = Modifier
                                .size(24.dp)
                                .padding(top = 8.dp)
                                .clickable {
                                    // 更新邮箱
                                    val newUserInfo =
                                        meViewModel.currentUserInfo.value.copy(email = inputEmail)
                                    meViewModel.updateUserInfo(
                                        userInfo = newUserInfo, context = context
                                    )
                                })
                    }
                }
                // 修改密码
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(10.dp)
                        .clickable {
                            scope.launch {
                                updatePasswordBottomSheetState.show()
                            }
                        },
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "更改密码",
                        fontSize = 14.sp,
                        color = InstagramDarkGray,
                        modifier = Modifier.weight(1f)
                    )
                    Image(painter = painterResource(id = R.drawable.arrow_forward),
                        contentDescription = "",
                        modifier = Modifier
                            .size(24.dp)
                            .padding(top = 8.dp)
                            .clickable {
                                scope.launch {
                                    updatePasswordBottomSheetState.show()
                                }
                            })
                }
            }
//            Divider(modifier = Modifier.fillMaxWidth(), color = InstagramLightGray)
//            // 个人信息设置
//            Text(
//                text = "个人信息设置",
//                color = InstagramBlue,
//                fontSize = 14.sp,
//                fontWeight = FontWeight.Bold,
//                modifier = Modifier.padding(10.dp)
//            )
//            Divider(modifier = Modifier.fillMaxWidth(), color = InstagramLightGray)
        }
    }
    // 性别抽屉
    ModalBottomSheetLayout(
        sheetState = genderBottomSheetState,
        sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
        sheetContent = {
            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 1.dp, bottom = 10.dp, start = 10.dp, end = 10.dp)
            ) {
                // 添加 Bar
                item {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentSize(align = Alignment.Center)
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.bar_horizontal),
                            contentDescription = "bar",
                        )
                    }
                }
                // 主要内容区域
                item {
                    Column(

                    ) {
                        //Spacer(modifier = Modifier.height(20.dp))
                        Text(
                            text = "性别",
                            fontSize = 18.sp,
                            modifier = Modifier.align(Alignment.CenterHorizontally)
                        )
                        androidx.compose.foundation.layout.Spacer(modifier = Modifier.height(10.dp))
                        Divider(modifier = Modifier.fillMaxWidth(), color = InstagramLightGray)
                        androidx.compose.foundation.layout.Spacer(modifier = Modifier.height(10.dp))
                        Text(
                            text = "设置性别",
                            fontSize = 15.sp,
                        )

                        androidx.compose.foundation.layout.Spacer(modifier = Modifier.height(15.dp))

                        Row(verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickableNoRipple {
                                    inputSex = 0
                                }) {
                            Image(painter = painterResource(id = R.drawable.grid),
                                contentDescription = null,
                                modifier = Modifier
                                    .size(30.dp)
                                    .clickable {
                                        scope.launch {

                                        }
                                    })
                            androidx.compose.foundation.layout.Spacer(modifier = Modifier.width(10.dp))
                            Text(
                                text = "男",
                                fontSize = 15.sp,
                            )
                            androidx.compose.foundation.layout.Spacer(modifier = Modifier.weight(1f))
                            Image(
                                painter = painterResource(id = if (inputSex == 0) R.drawable.circle_selected else R.drawable.circle_unselected),
                                contentDescription = null,
                                modifier = Modifier.size(20.dp)
                            )
                        }

                        androidx.compose.foundation.layout.Spacer(modifier = Modifier.height(20.dp))

                        Row(verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickableNoRipple {
                                    inputSex = 1

                                }) {
                            Image(painter = painterResource(id = R.drawable.video),
                                contentDescription = null,
                                modifier = Modifier
                                    .size(30.dp)
                                    .clickable {
                                        scope.launch {

                                        }
                                    })
                            androidx.compose.foundation.layout.Spacer(modifier = Modifier.width(10.dp))
                            Text(
                                text = "女",
                                fontSize = 15.sp,
                            )
                            androidx.compose.foundation.layout.Spacer(modifier = Modifier.weight(1f))
                            Image(
                                painter = painterResource(id = if (inputSex == 1) R.drawable.circle_selected else R.drawable.circle_unselected),
                                contentDescription = null,
                                modifier = Modifier.size(20.dp)
                            )
                        }

                        androidx.compose.foundation.layout.Spacer(modifier = Modifier.height(20.dp))

                        Row(verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickableNoRipple {
                                    inputSex = 2

                                }) {
                            Image(painter = painterResource(id = R.drawable.video),
                                contentDescription = null,
                                modifier = Modifier
                                    .size(30.dp)
                                    .clickable {
                                        scope.launch {

                                        }
                                    })
                            androidx.compose.foundation.layout.Spacer(modifier = Modifier.width(10.dp))
                            Text(
                                text = "未知",
                                fontSize = 15.sp,
                            )
                            androidx.compose.foundation.layout.Spacer(modifier = Modifier.weight(1f))
                            Image(
                                painter = painterResource(id = if (inputSex == 2) R.drawable.circle_selected else R.drawable.circle_unselected),
                                contentDescription = null,
                                modifier = Modifier.size(20.dp)
                            )
                        }

                        Row(
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            androidx.compose.material3.Button(
                                onClick = {
                                    scope.launch {
                                        // 更新性别
                                        meViewModel.updateUserInfo(
                                            meViewModel.currentUserInfo.value.copy(sex = inputSex),
                                            context
                                        )
                                        genderBottomSheetState.hide()
                                    }
                                },
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = InstagramBlue, contentColor = Color.White
                                ),
                                shape = RoundedCornerShape(10.dp),
                                modifier = Modifier
                                    .padding(top = 25.dp)
                                    .width(400.dp)
                            ) {
                                Text(text = "完成")
                            }
                        }
                    }
                }
            }
        }) {}
    // 修改密码抽屉
    ModalBottomSheetLayout(
        sheetState = updatePasswordBottomSheetState,
        sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
        sheetContent = {
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(top = 1.dp, bottom = 10.dp, start = 10.dp, end = 10.dp)
            ) {
                // 添加 Bar
                item {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentSize(align = Alignment.Center)
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.bar_horizontal),
                            contentDescription = "bar",
                        )
                    }
                }
                // 主要内容区域
                item {
                    var inputOldPassword by remember {
                        mutableStateOf("")
                    }
                    var inputNewPassword by remember {
                        mutableStateOf("")
                    }
                    var inputNewPasswordAgain by remember {
                        mutableStateOf("")
                    }
                    Column(
                        modifier = Modifier.fillMaxSize()
                            .weight(1f)
                    ) {

                        Text(
                            text = "更改密码",
                            fontSize = 18.sp,
                            modifier = Modifier.align(Alignment.Start)
                        )
                        TextField(
                            value = inputOldPassword,
                            onValueChange = { inputOldPassword = it },
                            placeholder = {
                                Text(
                                    text = "旧密码",
                                )
                            },
                            modifier = Modifier
                                .padding(vertical = 8.dp)
                                .heightIn(min = 30.dp, max = 56.dp),
                            colors = TextFieldDefaults.colors(
                                focusedIndicatorColor = LightGrayBackground,
                                unfocusedIndicatorColor = LightGrayBackground,
                                disabledIndicatorColor = LightGrayBackground,
                                unfocusedContainerColor = LightGrayBackground,
                            ),
                            shape = RoundedCornerShape(5.dp),
                        )

                        TextField(
                            value = inputNewPassword,
                            onValueChange = { inputNewPassword = it },
                            placeholder = {
                                Text(
                                    text = "新密码",
                                )
                            },
                            modifier = Modifier
                                .padding(vertical = 8.dp)
                                .heightIn(min = 30.dp, max = 56.dp),
                            colors = TextFieldDefaults.colors(
                                focusedIndicatorColor = LightGrayBackground,
                                unfocusedIndicatorColor = LightGrayBackground,
                                disabledIndicatorColor = LightGrayBackground,
                                unfocusedContainerColor = LightGrayBackground,
                            ),
                            shape = RoundedCornerShape(5.dp),
                        )

                        TextField(
                            value = inputNewPasswordAgain,
                            onValueChange = { inputNewPasswordAgain = it },
                            placeholder = {
                                Text(
                                    text = "再次输入新密码",
                                )
                            },
                            modifier = Modifier
                                .padding(vertical = 8.dp)
                                .heightIn(min = 30.dp, max = 56.dp),
                            colors = TextFieldDefaults.colors(
                                focusedIndicatorColor = LightGrayBackground,
                                unfocusedIndicatorColor = LightGrayBackground,
                                disabledIndicatorColor = LightGrayBackground,
                                unfocusedContainerColor = LightGrayBackground,
                            ),
                            shape = RoundedCornerShape(5.dp),
                        )
                    }

                    Row(
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        androidx.compose.material3.Button(
                            onClick = {
                                scope.launch {
                                    // 验证旧密码是否正确
                                    if (inputOldPassword == meViewModel.currentUserInfo.value.password) {
                                        // 验证新密码是否一致
                                        if (inputNewPassword == inputNewPasswordAgain) {
                                            // 更新密码
                                            meViewModel.updateUserInfo(
                                                meViewModel.currentUserInfo.value.copy(password = inputNewPassword),
                                                context
                                            )
                                            // 清空输入框
                                            inputOldPassword = ""
                                            inputNewPassword = ""
                                            inputNewPasswordAgain = ""
                                            updatePasswordBottomSheetState.hide()
                                        } else {
                                            Toast.makeText(
                                                context,
                                                "两次输入密码不一致",
                                                Toast.LENGTH_SHORT
                                            ).show()
                                        }
                                    } else {
                                        Toast.makeText(
                                            context,
                                            "旧密码错误",
                                            Toast.LENGTH_SHORT
                                        ).show()
                                    }
                                }
                            },
                            colors = ButtonDefaults.buttonColors(
                                containerColor = InstagramBlue, contentColor = Color.White
                            ),
                            shape = RoundedCornerShape(10.dp),
                            modifier = Modifier
                                .padding(top = 25.dp)
                                .width(400.dp)
                        ) {
                            Text(text = "更改密码")
                        }
                    }
                }
            }
        }) {}
}

@Composable
fun UpdateAvatar(
    userId: String,
    meViewModel: MeViewModel,
) {
    val context = LocalContext.current
    val imagePicker =
        rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent(),
            onResult = { uri ->
                if (uri != null) {
                    Log.d("avatar", "Selected image: $uri")
                    meViewModel.uploadImage(uri = uri, context = context, userId = userId)
                }
            })

    // 初始化加载服务器头像
    LaunchedEffect(key1 = userId) {
        meViewModel.loadServerAvatar(userId)
    }
    Row(
        modifier = Modifier.fillMaxWidth(),
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center,
            modifier = Modifier
                .padding(top = 20.dp)
                .fillMaxWidth()
        ) {
            // 头像显示区域
            val url = meViewModel.serverFileName?.let {
                "${Config.ADDRESS}avatars/$it"
            } ?: run {
                //context.getString(R.string.default_avatar_url) // 使用字符串资源
            }
            // 显示图片
            AsyncImage(
                model = url,
                contentDescription = "用户头像",
                modifier = Modifier
                    .size(100.dp)
                    .clip(CircleShape)
                    .clickable {
                        // 修改这里
                        imagePicker.launch("image/*")
                    },
                contentScale = ContentScale.Crop,
                error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
            )
            Spacer()
            // 修改按钮
            Box(
                modifier = Modifier
                    .width(200.dp)
                    .height(40.dp)
                    .clip(RoundedCornerShape(8.dp))
                    .background(InstagramLightGray)
                    .clickable {
                        // 打开文件管理器
                        imagePicker.launch("image/*")
                    },
                contentAlignment = Alignment.Center,
            ) {
                androidx.wear.compose.material3.Text(
                    text = "编辑头像", color = Color.Black
                )
            }
        }
    }
}

